import React, { useState, useEffect } from "react"
import {
  Row, Button, Select, Input, Table, Image, Form, Modal, DatePicker, Radio,
} from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import API from "../../api";
import "./hp.sass"
import useFilterData from "../../hooks/useFilterData";
import { formatDate } from "./../../utils";
import moment from "moment";
import UploadImage from "../../components/upload-image";
const { RangePicker } = DatePicker;


export default () => {
  const {
    currentData,
    total,
    isLoading,
    setPaginationParams,
    paginationParams,
    setFilterParams,
    getData
  } = useFilterData({
    api: API.getCompanys,
  });

  // 通过 Form.useForm 对表单数据域进行交互
  const [toolbarForm] = Form.useForm();

  // 保存 列表选中项的key;rlt:tool删除方法参数:
  const [selectedKeys, setSelectedKeys] = useState([])

  // 保存 许可证状态项
  const [validStatus, setValidStatus] = useState([])

  // 保存 经营类型项
  const [businessTypes, setBusinessTypes] = useState([])

  // ①保存 辖区项
  // ②请求 辖区信息
  // ③初始化完毕请求辖区信息
  const [areas, setAreas] = useState([])
  const ReqAreas = async () => {
    const tmp = await API.getAreas();
    tmp.push({ name: "全部", value: "" });
    console.log("辖区数据:", tmp);
    setAreas(tmp);
  }
  // 第二个参数加个空数组,模仿componentDidMount
  useEffect(() => {
    ReqAreas()
  }, [])

  // toolbar表单完成方法
  function FnFinToolbar() { }
  // 再次请求接口获取数据;rlt:tool刷新
  // const FnGetData = () => {
  //   return 
  // }
  // 是否显示新增表单弹窗.rtl tool新增,表单弹窗
  const [isModalVisible, setIsModalVisible] = useState(false)

  // 选中项删除.rlt:tool删除
  const FnDelItems = (keys) => {
    console.log(keys);
  }
  // 请求 删除
  const ReqDelData = (ids) => {
    Modal.confirm({
      title: "是否确定删除选中数据",
      cancelText: "取消",
      okText: "确定",
      icon: <ExclamationCircleOutlined />,
      onOk() {
        console.log("调用接口");
      }
    })
  }
  // 搜索筛选重置
  const FnFilterReset = () => {
    console.log("搜索筛选重置");
  }

  const columns = [
    {
      /**
       * 讯号就是我们的 1、2、3、4、
       */
      title: "序号",
      key: "id",
      render: (text, record, index) => <a>{index + 1}</a>,
    },
    {
      title: "所属辖区",
      dataIndex: "areaName",
      key: "id",
    },
    {
      title: "经营类型",
      dataIndex: "businessType",
      key: "id",
      width: 200,
      render: (text) => (
        <a>
          {businessTypes.find((item) => item.value === text) &&
            businessTypes.find((item) => item.value === text).label}
        </a>
      ),
    },
    {
      title: "门店名称",
      dataIndex: "storeName",
      key: "id",
    },
    {
      /**
       * 字段未找到,
       * 但是我们询问后端，他告诉我们，许可证开始日期+许可证结束日期就是有效期
       */
      title: "许可证有效期",
      key: "id",
      width: 240,
      render: (text, record) => {
        return (
          <a>
            {formatDate(record.validStartTime)} -
            {formatDate(record.validEndTime)}
          </a>
        );
      },
    },
    {
      /**
       * 字段未找到
       * 询问后端，该字段怎么获取，
       * 得到的结果是，直接拿licenceStatus 渲染即可
       */
      title: "许可证状态",
      dataIndex: "licenceStatus",
      key: "id",
      width: 150,
    },
    {
      title: "营业状态",
      dataIndex: "businessStatus",
      key: "id",
      render: (text, record) => {
        return <a>{text === "on" ? "营业中" : "暂停营业"}</a>;
      },
    },
    {
      title: "门头照片",
      dataIndex: "sotreImage",
      key: "id",
      render: (url) => (
        <div>
          <Image width={50} height={50} src={url} />
        </div>
      ),
    },
    {
      title: "量化等级",
      dataIndex: "quantizationLv",
      key: "id",
    },
    {
      title: "网络餐饮",
      dataIndex: "isOnLine",
      key: "id",
      render: (text) => <div>{text === 1 ? "是" : "否"}</div>,
    },
    {
      title: "阳光厨房",
      dataIndex: "isSunshine",
      key: "id",
      render: (text) => <div>{text === 1 ? "是" : "否"}</div>,
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "id",
    },
    {
      title: "操作",
      key: "id",
      fixed: "right",
      width: 180,
      render: (_, record) => (
        <div>
          <Button onClick={() => ReqDelData([record.id])}>删除</Button>
          &nbsp;&nbsp;
          <Button onClick={() => updateCompany(record)}>编辑</Button>
        </div>
      ),
    },
  ].map((item) => {
    return {
      width: 100,
      ...item,
    };
  });

  const totalNumber = 100

  const paginationChange = (page) => {
    // 修改分页数据
    setPaginationParams({
      ...paginationParams,
      page,
    });
  };

  const onSelectChange = (newSelectedRowKeys) => {
    /**
     * 如果这个数组为空的话，那么说明没有选择，就要disable
     */
    setSelectedKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    onChange: onSelectChange,
  };

  const dateFormatList = ["YYYY/MM/DD", "YYYY/MM/DD"];
  const [companyDataItem, setCompanyDataItem] = useState(null);

  const updateCompany = async (data) => {
    const res = await API.getCompanyDetail(data.id);

    if (res.validStartTime || res.validEndTime) {
      res.licenceDate = [
        moment(res.validStartTime, dateFormatList[0]),
        moment(res.validEndTime, dateFormatList[1]),
      ];
    }

    /**
     * 在antd 或者 element-ui等一系列的表单控件中
     * 所有的判断都是强类型判断
     */
    if (res.areaId) {
      res.areaId = res.areaId * 1;
    }
    setCompanyDataItem(res);
  };

  useEffect(() => {
    if (companyDataItem) {
      setIsModalVisible(true);
    }
  }, [companyDataItem]);


  const [createForm] = Form.useForm();
  // 新增模态框确认事件
  const handleModalOk = async () => {
    // 使用表单校验的方法，既可以校验表单，也可以拿到数据
    let data = await createForm.validateFields();

    // 劫持表单数据，并修改成后端需要的格式
    data = convertCompanyForm(data);

    /**
     * 把拿到的数据传给后端
     * 创建的时候，不需要接收返回值
     */
    const obj = companyDataItem || {};
    console.log(companyDataItem);
    await API[obj.id ? "updateCompany" : "createCompany"](data);

    createForm.resetFields();

    /**
     * 刷新列表
     */
    getData();
    setIsModalVisible(false);
  };
  // 新增模态框取消事件
  const handleModalCancel = () => {
    createForm.resetFields();
    setIsModalVisible(false);
  };
  useEffect(() => {
    if (!isModalVisible) {
      setCompanyDataItem(null);
    }
  }, [isModalVisible]);
  // 把表单转换成后端需要的格式
  const convertCompanyForm = (data) => {
    if (data.licenceDate) {
      data.validStartTime = data.licenceDate[0];
      data.validEndTime = data.licenceDate[1];
    }

    const obj = companyDataItem || {};

    data.sotreImage = companyDataItem
      ? companyDataItem.sotreImage
      : data.sotreImage;
    data.id = obj.id;
    return data;
  };

  // 上传功能
  const uploadSuccess = (sotreImage) => {
    const obj = companyDataItem || {};
    setCompanyDataItem({
      sotreImage,
      ...obj,
    });
  };

  /**
   * 通过form里面内置的hook，来监听对应字段的变化
   * 来达到变化
   * 注意：要把监听的表单实例传进去
   *
   * useWatch 的实现思路
   *
   * 首先监听传入的form实例，当实例里面的表单发生变化的时候
   * 进行判断，判断变化的字段是否为我们传入的第一个参数字段名
   * 如果是，则把当前变化的值传出来
   */
  const isOnLine = Form.useWatch("isOnLine", createForm);

  return (

    <div className="hp">
      {/* toolbar */}
      <Row className="topBar">
        <div className="btnGroup">
          <Button onClick={getData}>刷新</Button>
          <Button type="primary" onClick={() => setIsModalVisible(true)}>
            新增
          </Button>
          <Button
            type="danger"
            onClick={() => FnDelItems(selectedKeys)}
            disabled={selectedKeys.length === 0}>
            删除
          </Button>
          <Button>导出</Button>
        </div>
        <div className="searchGroup">
          <Form
            name="basic"
            // labelCol={{ span: 8 }}
            // wrapperCol={{ span: 16 }}
            onFinish={FnFinToolbar}
            autoComplete="off"
            form={toolbarForm}
          >
            <Form.Item label="所属辖区" name="areaId">
              <Select>
                {areas.map((item) => (
                  <Select.Option key={item.name} value={item.id}>
                    {item.name}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item label="经营类型" name="businessType">
              <Select>
                {businessTypes.map((item) => (
                  <Select.Option key={item.label} value={item.value}>
                    {item.label}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item label="许可证状态" name="validStatus">
              <Select>
                {validStatus.map((item) => (
                  <Select.Option key={item.label} value={item.value}>
                    {item.label}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item name="keyWord">
              <Input placeholder="请输入" className="kotei"></Input>
            </Form.Item>

            <div className="btnGroup">
              <Button type="primary" htmlType="submit">
                搜索
              </Button>
              <Button onClick={FnFilterReset} htmlType="button">
                重置
              </Button>
            </div>
          </Form>
        </div>
      </Row>
      <Row>
        <Table
          style={{ marginTop: "20px" }}
          columns={columns}
          dataSource={currentData}
          scroll={{
            x: 800,
            y: 200,
          }}
          pagination={{
            totalNumber,
            defaultPageSize: paginationParams.size,
            onChange: paginationChange,
          }}
          loading={isLoading}
          rowSelection={rowSelection}
        />
      </Row>
      {/* toolbar end */}
      <Row>
        <Modal
          title="新增"
          visible={isModalVisible}
          onOk={handleModalOk}
          onCancel={handleModalCancel}
        >
          <Form
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            initialValues={companyDataItem}
            autoComplete="off"
            form={createForm}
          >
            <Form.Item label="所属辖区" name="areaId">
              <Select style={{ width: 120 }}>
                {areas
                  .filter((item) => !!item.id)
                  .map((item) => (
                    <Select.Option key={item.name} value={item.id}>
                      {item.name}
                    </Select.Option>
                  ))}
              </Select>
            </Form.Item>
            <Form.Item label="经营类型" name="businessType">
              <Select style={{ width: 120 }}>
                {businessTypes
                  .filter((item) => !!item.value)
                  .map((item) => (
                    <Select.Option key={item.label} value={item.value}>
                      {item.label}
                    </Select.Option>
                  ))}
              </Select>
            </Form.Item>
            <Form.Item label="门店名称" name="storeName">
              <Input></Input>
            </Form.Item>
            <Form.Item label="单位名称" name="companyName">
              <Input></Input>
            </Form.Item>
            <Form.Item label="许可证号" name="licenceNum">
              <Input></Input>
            </Form.Item>
            <Form.Item label="有效日期" name="licenceDate">
              <RangePicker />
            </Form.Item>
            <Form.Item label="社会统一信用代码" name="socialCreditCode">
              <Input></Input>
            </Form.Item>
            <Form.Item label="门店地址" name="storeAddress">
              <Input></Input>
            </Form.Item>
            <Form.Item label="营业状态" name="businessStatus">
              <Radio.Group>
                <Radio value={"on"}>正常营业</Radio>
                <Radio value={"off"}>暂停营业</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item label="法人" name="legalPerson">
              <Input></Input>
            </Form.Item>
            <Form.Item label="联系电话" name="tel">
              <Input></Input>
            </Form.Item>
            <Form.Item label="门店照片" name="sotreImage">
              <UploadImage uploadSuccess={uploadSuccess}></UploadImage>
            </Form.Item>
            <Form.Item label="量化等级" name="quantizationLv">
              <Radio.Group>
                <Radio value={"A"}>A</Radio>
                <Radio value={"B"}>B</Radio>
                <Radio value={"C"}>C</Radio>
                <Radio value={"D"}>未定级</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item label="网络餐饮" name="isOnLine">
              <Radio.Group>
                <Radio value={true}>是</Radio>
                <Radio value={false}>否</Radio>
              </Radio.Group>
            </Form.Item>
            {isOnLine && (
              <Form.Item label="阳光厨房" name="isSunshine">
                <Radio.Group>
                  <Radio value={true}>是</Radio>
                  <Radio value={false}>否</Radio>
                </Radio.Group>
              </Form.Item>
            )}
          </Form>
        </Modal>
      </Row>

    </div>
  )
}